<?php
/*
	[Xiuno] (C)2008-2009
	This is NOT a freeware, use is subject to license terms

	$RCSfile: index.php,v $
	$Revision: 1.0 $
	$Date: 2009/05/5 14:36:00 $
	$Author: heyond $
*/

/**

用法：

上传控件名称
<form action="" type="post" type="data/enctype">
<input type="file" name="attach[]">
<input type="file" name="attach[3]">
</form>

PHP生成的数组如下:
Array
(
    [attach] => Array
        (
            [name] => Array
                (
                    [0] => index_4.jpg
                    [1] =>
                    [2] =>
                    [3] =>
                )

            [type] => Array
                (
                    [0] => image/pjpeg
                    [1] =>
                    [2] =>
                    [3] =>
                )

            [tmp_name] => Array
                (
                    [0] => C:\WINDOWS\TEMP\php70.tmp
                    [1] =>
                    [2] =>
                    [3] =>
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 4
                    [2] => 4
                    [3] => 4
                )

            [size] => Array
                (
                    [0] => 7324
                    [1] => 0
                    [2] => 0
                    [3] => 0
                )

        )

)

include XIUNO_ROOT.'lib/upload.class.php';
$u = new Upload();
//$u->set_save_type('HASH');//HASH|DATE
$attachurl = XIUNO_ATTACH_URL;
$attachdir = XIUNO_ATTACH_DIR;
$u->set_dir($attachdir, $attachurl);
$u->set_thumb(100, 100);
$arr = $u->execute();

foreach($arr as $key=>$file) {
	$this->db->query("INSERT INTO www_attachments SET filename='$file[file]', filesize='$file[size]', havethumb='0', uid='$this->user[uid]'");
	$aid = $this->db->insert_id();
	if($file['thumb']) {
		$this->db->query("UPDATE www_attachments SET havethumb='1' WHERE aid='$aid'");
	}
}
*/
Class Upload {

	private $dir;
	private $url;
	private $width;		// 原图的宽高
	private $height;	// 原图的宽高
	private $thumb_width;	// 缩略图的宽高
	private $thumb_height;	// 缩略图的宽高
	private $thumb_ext;	// 缩略图的类型 gif jpg
	private $watermark_file;
	private $watermark_pos;
	private $watermark_alpha;
	private $watermark_on;
	private $time;

	public $filetypedata = array(); //允许的文件类型
	public $filetypeids = array(); //允许的文件类型
	public $filetypes = array(); //允许的文件类型
	public $imagemagickdir;		// 插件路径

	public $savetype = 'DATE';

	function __construct($time = 0) {
		$this->time = $time ? $time : time();
		$this->filetypedata = array(
			'av' => array('av', 'wmv', 'wav', 'wma', 'avi'),
			'real' => array('rm', 'rmvb'),
			'mp3' => array('mp3','mp4'),
			'binary' => array('dat'),
			'flash' => array('swf'),
			'html' => array('html', 'htm'),
			'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
			'office' => array('doc', 'xls', 'ppt'),
			'pdf' => array('pdf'),
			'rar' => array('rar'),
			'text' => array('txt'),
			'bt' => array('bt'),
			'zip' => array('tar','zip', 'gz'),
			'book' => array('chm'),
			'torrent' => array('torrent')
		);
		$this->filetypeids = array_keys($this->filetypedata);
		foreach($this->filetypedata as $data) {
			$this->filetypes = array_merge($this->filetypes, $data);
		}
		$this->imagemagickdir = (defined('XIUNO_IMAGEMAGICK_DIR') && XIUNO_IMAGEMAGICK_DIR) ? XIUNO_IMAGEMAGICK_DIR : '';
		$this->watermark_file = (defined('XIUNO_WATER_FILE') && XIUNO_WATER_FILE) ? XIUNO_ROOT.'/'.XIUNO_WATER_FILE : '';
		$this->watermark_on = (defined('XIUNO_WATERMARK_ON') && XIUNO_WATERMARK_ON && $this->watermark_file) ? XIUNO_WATERMARK_ON : 0;
	}

	public function set_save_type($savetype = 'DATE') {
		$this->savetype = $savetype;
	}

	public function set_dir($dir, $url) {
		if(!is_dir($dir)) {
			mkdir($dir, 0777, true);
		}
		$this->dir = $dir;
		$this->url = $url;
	}

	public function set_allowext($ext) {
		$this->filetypedata = $ext;
	}

	public function set_width_height($width = 100, $height = 100) {
		$this->width = $width;
		$this->height = $height;
	}

	public function set_thumb($width, $height, $ext = '') {
		$this->thumb_width = $width;
		$this->thumb_height = $height;
		$this->thumb_ext = $ext;
	}

	public function set_watermark($file, $pos = 9, $alpha = 100) {
		$this->watermark_file = $file;
		$this->watermark_pos = $pos;
		$this->watermark_alpha = $alpha;
	}

	public function execute() {
		$return = array();
		//附件数量
		$keys = array_keys($_FILES['attach']['name']);
		$dir = $url = '';
		foreach($keys as $key) {
			if(empty($_FILES['attach']['name'][$key]) || empty($_FILES['attach']['tmp_name'][$key])) {
				continue;
			}
			$file = array(
				'size' => $_FILES['attach']['size'][$key],
				'name' => $_FILES['attach']['name'][$key],
				'tmp_name' => $_FILES['attach']['tmp_name'][$key]
			);
			$fileext = $this->fileext($file['name']);
			$filetype = $this->get_filetype($fileext);
			if(!$filetype) {
				continue;
			}
			$filepre = $this->filepre($file['name']);

			// 生成目录
			if($this->savetype == 'HASH') {
				$s = $this->mkdir_by_hash($filepre, $this->dir);
				$dir = $this->dir.'/'.$s;
				$url = $this->url.'/'.$s;
			} elseif($this->savetype == 'DATE') {
				$s = $this->mkdir_by_date($this->time, $this->dir);
				$dir = $this->dir.'/'.$s;
				$url = $this->url.'/'.$s;
			} elseif($this->savetype == 'ID') {
				$dir = $this->dir;
				$url = $this->url;
			}

			// 设置文件名称， 最后两个参数为缺省参数。缺省时，支持中文名称
			$filename = $this->filename($file['name'], $dir, $fileext, $this->time, $key);
			$thumbname = $this->thumbname($file['name'], $dir, $fileext, $this->time, $key);
			if(empty($filename)) {
				continue;
			}

			$this->copy($file['tmp_name'], $dir.'/'.$filename);
			$return[$key] = array();
			$return[$key]['fileurl'] = $url.'/'.$filename;
			$return[$key]['filepath'] = $dir.'/'.$filename;
			$return[$key]['filesize'] = $file['size'];
			$return[$key]['type'] = $filetype;
			$return[$key]['orgfilename'] = addslashes(htmlspecialchars($_FILES['attach']['name'][$key]));
			if($filetype == 'image') {
				// 调整原图大小
				if($this->width) {
					$return[$key]['filesize'] =  $this->thumb($this->width, $this->height, $dir.'/'.$filename, $dir.'/'.$filename, 'jpg', 25, 0, 0, $this->imagemagickdir);
				}
				// 缩略图
				if($this->thumb_width && $return[$key]['filesize']) {
					if($thumbsize = $this->thumb($this->thumb_width, $this->thumb_height, $dir.'/'.$filename, $dir.'/'.$thumbname, ($this->thumb_ext ? $this->thumb_ext : $fileext), 25, 0, 1, $this->imagemagickdir)) {
						$return[$key]['thumburl'] = $url.'/'.$thumbname;
						$return[$key]['thumbpath'] = $dir.'/'.$thumbname;
						$return[$key]['thumbsize'] = $thumbsize;
					}
				}
				list($width, $height) = getimagesize($dir.'/'.$filename);
				$return[$key]['width'] = $width;
				$return[$key]['height'] = $height;
				if($this->watermark_on && $width > 400 && $height > 400) {
					$this->watermark($dir.'/'.$filename, $this->watermark_file, $fileext, 9, 50, $this->imagemagickdir);
				}
			} else if($filetype == 'torrent') {
				include_once "./lib/bdecode.class.php";
				$o = new Bdecode;
				$torrentinfo = $o->decode(file_get_contents($dir.'/'.$filename));
				$return[$key]['torrentinfo'] = $torrentinfo;
			}
		}
		return $return;
	}

	public function mkdir_by_date($date, $dir = '.') {
		list($y, $m, $d) = explode('-', date('Y-m-d', $date));
		!is_dir("$dir/$y") && mkdir("$dir/$y", 0777);
		!is_dir("$dir/$y/$m$d") && mkdir("$dir/$y/$m$d", 0777);
		return "$y/$m$d";
	}

	public function mkdir_by_hash($s, $dir = '.') {
		$s = md5($s.'randomstring123');
		$s1 = substr($s, 0, 2);
		$s2 = substr($s, 2, 2);
		$dir1 = $dir."/$s1";
		$dir2 = $dir."/$s1/$s2";

		!is_dir($dir1) && mkDirs($dir1, 0777);
		!is_dir($dir2) && mkDirs($dir2, 0777);
		return "$s1/$s2";
	}

	public function copy($sourcefile, $destfile) {
		move_uploaded_file($sourcefile, $destfile);
		file_exists($sourcefile) && unlink($sourcefile);
	}
	
	/**
	 * 上传文件，返回上传地址
	 *
	 * @param unknown_type $file
	 * @param 生成地址不需要绝对路经
	 * @return unknown
	 */
	public function upfile(&$file, $dir = '.'){
		if(!$file['name']) {
			return '';
		}
		$mkdir = $this->mkdir_by_hash($file['name'], GODHOUSE_ROOT.$dir);
		$fileext = $this->fileext($file['name']);
		$filename = $this->filename($file['name'], $mkdir, $fileext, $this->time);
		$tofile = $dir.'/'.$mkdir.'/'.$filename;
		$this->copy($file['tmp_name'], GODHOUSE_ROOT.$tofile);
		return '/'.$tofile;
	}

	/**
	 * 为图片添加水印
	 *
	 * @param string $target		原图地址
	 * @param string $watermark_file	水印图片地址
	 * @param string $ext			允许加水印的图片类型
	 * @param int $watermarkstatus		水印位置
	 * @param int $watermarktrans		水印透明度
	 * @param string $imagemagickdir	插件路径
	 * @return boolean
	 */
	public function watermark($target, $watermark_file, $ext, $watermarkstatus=9, $watermarktrans=50, $imagemagickdir='') {
		if(!is_file($watermark_file) || !file_exists($target)) {
			return false;
		}
		$animatedgif 	= 0;
		$imageinfo 	= getimagesize($target);
		$waterinfo 	= getimagesize($watermark_file);
		$img_w		= $imageinfo[0];
		$img_h		= $imageinfo[1];
		$logo_w 	= $waterinfo[0];
		$logo_h		= $waterinfo[1];
		$wmwidth	= $img_w - $logo_w;
		$wmheight	= $img_h - $logo_h;
		if($wmwidth <= 10 || $wmheight <= 10) {
			return false;
		}

		if($imageinfo['mime'] == 'image/gif') {
			$fp = fopen($target, 'rb');
			$targetcontent = fread($fp, 9999999);
			fclose($fp);
			$animatedgif = strpos($targetcontent, 'NETSCAPE2.0') === FALSE ? 0 : 1;
		}

		// 小于2M的gif动画图片，利用外部插件处理
		if($animatedgif && !empty($imagemagickdir) && filesize($target) <= 400000) {
			$cmd   = '"'.$imagemagickdir.'composite"';
			$cmd .= ' -dissolve ' . $watermarktrans;
			$cmd .= ' -gravity SouthEast';
			$cmd .= ' ' . $watermark_file;
			$cmd .= ' ' . $target;
			$cmd .= ' ' . $target;
			$ret = 100;
			$out = array();
			exec($cmd,$out,$ret);
			return !$ret;
		}

		if($animatedgif) {
			return false;
		}

		// gd库函数添加水印
		$gdsurporttype = array();
		if(function_exists('imageAlphaBlending') && function_exists('getimagesize')) {
			if(function_exists('imageGIF')) $gdsurporttype[]='gif';
			if(function_exists('imagePNG')) $gdsurporttype[]='png';
			if(function_exists('imageJPEG')) {
				$gdsurporttype[]='jpg';
				$gdsurporttype[]='jpeg';
			}
		}
		if($gdsurporttype && in_array($ext, $gdsurporttype)) {
			switch ($waterinfo['mime']) {
				case 'image/jpeg':
					$watermark_logo = imagecreatefromjpeg($watermark_file);
					!$watermark_logo && $watermark_logo = imagecreatefromgif($watermark_file);
					break;
				case 'image/gif':
					$watermark_logo = imageCreateFromGIF($watermark_file);
					break;
				case 'image/png':
					$watermark_logo = imageCreateFromPNG($watermark_file);
					break;
			}

			switch ($imageinfo['mime']) {
				case 'image/jpeg':
					$dst_photo = imagecreatefromjpeg($target);
					!$dst_photo && $dst_photo = imagecreatefromgif($target);
					break;
				case 'image/gif':
					$dst_photo = imageCreateFromGIF($target);
					break;
				case 'image/png':
					$dst_photo = imageCreateFromPNG($target);
					break;
			}

			switch($watermarkstatus) {
				case 1:
					$x = +5;
					$y = +5;
					break;
				case 2:
					$x = ($logo_w +	$img_w)	/ 2;
					$y = +5;
					break;
				case 3:
					$x = $img_w - $logo_w-5;
					$y = +5;
					break;
				case 4:
					$x = +5;
					$y = ($logo_h +	$img_h)	/ 2;
					break;
				case 5:
					$x = ($logo_w +	$img_w)	/ 2;
					$y = ($logo_h +	$img_h)	/ 2;
					break;
				case 6:
					$x = $img_w - $logo_w;
					$y = ($logo_h +	$img_h)	/ 2;
					break;
				case 7:
					$x = +5;
					$y = $img_h - $logo_h-5;
					break;
				case 8:
					$x = ($logo_w +	$img_w)	/ 2;
					$y = $img_h - $logo_h;
					break;
				case 9:
					$x = $img_w - $logo_w-5;
					$y = $img_h - $logo_h-5;
					break;
			}

			imageAlphaBlending($watermark_logo, true);
			imagecopy($dst_photo, $watermark_logo, $x, $y, 0, 0, $logo_w,$logo_h);
			switch($imageinfo['mime']) {
				case 'image/jpeg':
					imageJPEG($dst_photo, $target);
					break;
				case 'image/gif':
					imageGIF($dst_photo, $target);
					break;
				case 'image/png':
					imagePNG($dst_photo, $target);
					break;
			}
			return true;
		}
		return false;
	}

	/**
	 * 图片缩略
	 *
	 * @param int $forcedwidth	缩略图宽
	 * @param int $forcedheight 	缩略图高
	 * @param string $sourcefile 	原图地址
	 * @param string $destfile 	缩略图存放地址
	 * @param string $destext 	缩略图格式
	 * @param int $imgcomp 		缩略图质量
	 * @param int $rect 		是否剪切
	 * @param int $strict 		是否严格限制图片大小
	 * @param string $imagemagickdir 外部插件路径
	 * @return int 			返回图片大小
	 */
	public function thumb($forcedwidth, $forcedheight, $sourcefile, $destfile, $destext='jpg', $imgcomp=25, $rect=1, $strict=0, $imagemagickdir='') {
		if(!file_exists($sourcefile)) {
			return 0;
		}

		$x = 0;
		$y = 0;
		$animatedgif = 0;
		$imgcomp = 100 - $imgcomp;
		$imginfo = getimagesize($sourcefile);
		$src_width = $imginfo[0];
		$src_height = $imginfo[1];
		$src_scale = $src_width / $src_height;
		$des_scale = $forcedwidth / $forcedheight;

		if($imginfo['mime'] == 'image/gif') {
			$fp = fopen($sourcefile, 'rb');
			$targetcontent = fread($fp, 9999999);
			fclose($fp);
			$animatedgif = strpos($targetcontent, 'NETSCAPE2.0') === FALSE ? 0 : 1;
			$destext = $animatedgif ? 'gif' :  $destext;
		}

		// 小于2M的gif动画图片，利用外部插件处理
		if($animatedgif && !empty($imagemagickdir) && filesize($sourcefile) <= 400000) {
			if($src_scale > $des_scale) {
				$forcedheight = $src_height > $forcedheight ? $forcedheight : $src_height;
				$forcedwidth = $forcedheight * $src_scale;
			} else {
				$forcedwidth = $src_width > $forcedwidth ? $forcedwidth : $src_width;
				$forcedheight = $forcedwidth / $src_scale;
			}

			$modifier = $strict ? '!' : '>';
		        $cmd  = '"'.$imagemagickdir.'convert"';
		        $cmd .= ' '.$sourcefile.' -coalesce ';
		        $cmd .= ($destext != 'gif') ? ' -flatten' : '';
		        $cmd .= ' -scale '.$forcedwidth.'x'.$forcedheight.$modifier.' -quality '.$imgcomp.' -strip '.$destfile;
			$ret = 100;
			$out = array();
			exec($cmd,$out,$ret);
			return filesize($destfile);
		}

		// 如果没有对图片大小进行严格限制，且传入的图片过小，则直接拷贝并且返回。
		if(!$strict && $src_width <= $forcedwidth && $src_height <= $forcedheight) {
			copy($sourcefile, $destfile);
			return filesize($destfile);
		}

		// 是否剪切，$rect=1剪切，$rect=0不剪切
		if($rect) {
			// 如果原图宽高比大于规定宽高比，则横向裁剪图片使宽高比例与规定相等
			if($src_scale > $des_scale && $src_width > $forcedwidth) {
				$newwidth = $src_height * $des_scale;
				$newwidth = ($newwidth < $forcedwidth) ? $forcedwidth : $newwidth;
				$x = ($src_width - $newwidth) / 2;
				$src_width = $newwidth;

			// 如果原图宽高比小于规定宽高比，则纵向裁剪图片使宽高比例与规定相等；
			} elseif($src_scale < $des_scale  && $src_height > $forcedheight) {
				$newheight = $src_width / $des_scale;
				$newheight = ($newheight < $forcedheight) ? $forcedheight : $newheight;
				$y = ($src_height - $newheight) / 2;
				$src_height = $newheight;
			}

			$src_scale = $src_width / $src_height;
		}

		// 按规定比例缩略
		if($src_width <= $forcedwidth && $src_height <= $forcedheight) {
			$des_width = $src_width;
			$des_height = $src_height;
		} elseif($src_scale >= $des_scale) {
			$des_width = ($src_width >= $forcedwidth) ? $forcedwidth : $src_width;
			$des_height = $des_width / $src_scale;
			$des_height = ($des_height >= $forcedheight) ? $forcedheight : $des_height;
		} else {
			$des_height = ($src_height >= $forcedheight) ? $forcedheight : $src_height;
			$des_width = $des_height * $src_scale;
			$des_width = ($des_width >= $forcedwidth) ? $forcedwidth : $des_width;
		}

		switch ($imginfo['mime']) {
			case 'image/jpeg':
				$img_src = @imagecreatefromjpeg($sourcefile);
				!$img_src && $img_src = imagecreatefromgif($sourcefile);
				break;
			case 'image/gif':
				$img_src = @imagecreatefromgif($sourcefile);
				!$img_src && $img_src = imagecreatefromjpeg($sourcefile);
				break;
			case 'image/png':
				$img_src = imagecreatefrompng($sourcefile);
				break;
			case 'image/wbmp':
				$img_src = imagecreatefromwbmp($sourcefile);
				break;
			default :
				return 0;
		}

		// 如果是严格限制图片大小则补白，否则按比例缩略
		if($strict) {
			$img_dst = imagecreatetruecolor($forcedwidth, $forcedheight);
			$bg = imagecolorallocate($img_dst, 255, 255, 255);
			imagefill($img_dst, 0, 0, $bg);
			$des_x = ($forcedwidth - $des_width) / 2;
			$des_y = ($forcedheight - $des_height) / 2;
			imagecopyresampled($img_dst, $img_src, $des_x, $des_y, $x, $y, $des_width, $des_height, $src_width, $src_height);
		} else {
			$img_dst = imagecreatetruecolor($des_width, $des_height);
			imagecopyresampled($img_dst, $img_src, 0, 0, $x, $y, $des_width, $des_height, $src_width, $src_height);
		}

		switch($destext) {
			case 'jpg':
				imagejpeg($img_dst, $destfile, $imgcomp);
				break;
			case 'gif':
				imagegif($img_dst, $destfile, $imgcomp);
				break;
		}
		imagedestroy($img_dst);
		return filesize($destfile);
	}

	/**
	 * 图片旋转
	 *
	 * @param string $sourcefile
	 * @param int $angle 旋转角度(0不旋转, 1旋转90°, 2旋转180°, 3旋转270°)
	 * @param string $destext 图片格式
	 * @param int $imgcomp	图片质量
	 * @param string $imagemagickdir 外部插件路径
	 * @return bool
	 */
	public function rotate($sourcefile, $angle, $destext='jpg', $imgcomp=25, $imagemagickdir='') {
		if(($angle!=1)&&($angle!=2)&&($angle!=3) || !file_exists($sourcefile)) {
			return false;
		}
		$imgcomp = 100-$imgcomp;
		$imageinfo = getimagesize($sourcefile);
		$g_iw = $imageinfo[0];
		$g_ih = $imageinfo[1];
		$animatedgif = 0;
		if($imageinfo['mime'] == 'image/gif') {
			$fp = fopen($sourcefile, 'rb');
			$targetcontent = fread($fp, 9999999);
			fclose($fp);
			$animatedgif = strpos($targetcontent, 'NETSCAPE2.0') === FALSE ? 0 : 1;
		}

		// 小于2M的gif动画图片，利用外部插件处理
		if($animatedgif && !empty($imagemagickdir) && filesize($sourcefile) <= 400000) {
			$angles = array(0, 90, 180, 270);
			$angle = isset($angles[$angle]) ? $angles[$angle] : $angle;
			$cmd   = '"'.$imagemagickdir.'convert"';
			$cmd .= " $sourcefile -coalesce -rotate $angle $sourcefile";
			$ret = 100 ;
			$out = array();
			exec($cmd,$out,$ret);
			return !$ret;
		}

		if($animatedgif) {
			return false;
		}

		// gd库函数旋转
		switch ($imageinfo['mime']) {
			case 'image/jpeg':
				$img_src = @imagecreatefromjpeg($sourcefile);
				!$img_src && $img_src = imagecreatefromgif($sourcefile);
				break;
			case 'image/gif':
				$img_src = @imagecreatefromgif($sourcefile);
				!$img_src && $img_src = imagecreatefromjpeg($sourcefile);
				break;
			case 'image/png':
				$img_src = imagecreatefrompng($sourcefile);
				break;
			case 'image/wbmp':
				$img_src = imagecreatefromwbmp($sourcefile);
				break;
			default :
				return false;
		}

		if(($angle==1)||($angle==3)) {
			$img_dst = ImageCreateTrueColor($g_ih, $g_iw);
		} else {
			$img_dst = ImageCreateTrueColor($g_iw, $g_ih);
		}
		switch($angle) {
			case 1:
				for($i=0;$i<$g_iw;$i++) {
					for($j=0;$j<$g_ih;$j++) {
						ImageSetPixel($img_dst, $g_ih-$j-1, $i, ImageColorAt($img_src, $i, $j));
					}
				}
				break;
			case 2:
				for($i=0;$i<$g_iw;$i++) {
					for($j=0; $j<$g_ih; $j++) {
						ImageSetPixel($img_dst, $g_iw-$i-1, $g_ih-$j-1, ImageColorAt($img_src, $i, $j));
					}
				}
				break;
			case 3:
				for($i=0;$i<$g_iw;$i++) {
					for($j=0;$j<$g_ih;$j++) {
						ImageSetPixel($img_dst, $j, $g_iw-$i-1, ImageColorAt($img_src, $i, $j));
					}
				}
				break;
		}

		switch($destext) {
			case 'jpg':
				imagejpeg($img_dst, $sourcefile, $imgcomp);
				break;
			case 'gif':
				imagegif($img_dst, $sourcefile, $imgcomp);
				break;
		}
		imagedestroy($img_dst);
		return true;
	}

	public function fileext($filename) {
		$fileext = strtolower(substr(strrchr($filename, '.'), 1, 10));
		if(!in_array($fileext, $this->filetypes)) {
			$fileext = '_'.$fileext;
		}
		return $fileext;
	}

	/**
	 * 获取文件名称
	 *
	 * @param string $filename
	 * @param string $dir
	 * @param string $fileext
	 * @param string $time		缺省时，支持中文名称
	 * @param int $attachkey
	 * @return string
	 */
	public function filename($filename, $dir, $fileext, $time = '', $attachkey = 0) {
		if(!empty($time)) {
			$attachkey = substr($attachkey, 0, 6);
			return $this->filepre($filename)."_{$attachkey}_".$time.'.'.$fileext;
		}

		$s = substr($filename, 0, strrpos($filename, '.'));
		$patterns = array("/[\.\\\\\/<>:*?\"|%\s\+0x00\r\n&]/", "/[\.]{2,}/");
		$replacements = array('', '.');
		$s = preg_replace($patterns, $replacements, $s);
		$filepre = $this->madhouse_substr($s, 0, 200);

		if(!file_exists($dir.'/'.$filepre.'.'.$fileext)) {
			return $filepre.'.'.$fileext;
		}
		for($i=1; $i<=100; $i++) {
			if(!file_exists($dir.'/'.$filepre.'_'.$i.'.'.$fileext)) {
				return $filepre.'_'.$i.'.'.$fileext;
			}
		}
		return '';
	}
	
	// substr for gbk
	// start only for '0'
	private function madhouse_substr($s, $len) {
		$s = substr($s, 0, $len);
		$len = min(strlen($s), $len);
		for($i=0; $i<$len; $i++) {
			ord($s[$i]) > 127 && $i++;
		}
		return ($i == $len) ? $s : substr($s, 0, -1);
	}

	/**
	 * 获取缩略图名称
	 *
	 * @param string $filename
	 * @param string $dir
	 * @param string $fileext
	 * @param string $time		缺省时，支持中文名称
	 * @param int $attachkey
	 * @return string
	 */
	public function thumbname($filename, $dir, $fileext, $time = '', $attachkey = 0) {
		if(!empty($time)) {
			$attachkey = substr($attachkey, 0, 6);
			return $this->filepre($filename)."_{$attachkey}_".$time.'_thumb.'.$fileext;
		}

		$s = substr($filename, 0, strrpos($filename, '.'));
		$patterns = array("/[\.\\\\\/<>:*?\"|%\s\+0x00\r\n&]/", "/[\.]{2,}/");
		$replacements = array('', '.');
		$s = preg_replace($patterns, $replacements, $s);
		$filepre = base::xiuno_substr($s, 0, 200);

		if(!file_exists($dir.'/'.$filepre.'.'.$fileext)) {
			return $filepre.'_thumb.'.$fileext;
		}
		for($i=1; $i<=100; $i++) {
			if(!file_exists($dir.'/'.$filepre.'_'.$i.'.'.$fileext)) {
				return $filepre.'_'.$i.'_thumb.'.$fileext;
			}
		}
		return '';
	}

	private function filepre($filename) {
		$s = urlencode(substr($filename, 0, strrpos($filename, '.')));
		return substr(preg_replace("/[\.\\\\\/<>:*?\"|%\s\+]/", '_', $s), 0, 26);
	}

	public function get_filetype($ext) {
		foreach($this->filetypedata as $k=>$v) {
			if(in_array($ext, $v)) {
				return $k;
			}
		}
		return '';
	}

	public function file_to_html($fileurl, $filetype, $extra = array()) {
		$imageid = !empty($extra['imageid']) ? $extra['imageid'] : 0;
		$downloads = !empty($extra['downloads']) ? $extra['downloads'] : 0;
		$dateline = !empty($extra['dateline']) ? '上传于 '.$extra['dateline'] : '';
		if($filetype == 'image') {
			list($imagewidth, $imageheight) = getimagesize($fileurl);
			$rate = $imageheight/$imagewidth;
			$imagewidth = $imagewidth >= 740 ? 740 : $imagewidth;
			$imageheight = intval($rate*$imagewidth);
			$dir = substr($fileurl, 0, strrpos($fileurl, '/'));
			$filename = substr($fileurl, strrpos($fileurl, '/')+1);
			$fileurl = $dir.'/'.urlencode($filename);
			return '<a href="'.$fileurl.'"'.(isset($extra['align']) ? " align=\"$extra[align]\"" : '').' target="_blank"><img src="'.XIUNO_HOST_IMAGE.$fileurl.'" width="'.$imagewidth.'" height="'.$imageheight.'" /></a>'."<!--imageid=$imageid-->";
		} elseif($filetype == 'flash') {
			return '<embed src="'.$fileurl.'" width="400" height="300"></embed>';
		} elseif($filetype == 'torrent') {
			$filename = htmlspecialchars(substr($fileurl, strrpos($fileurl, '/') + 1));
			$orgfilename = !empty($extra['orgfilename']) ? $extra['orgfilename'] : $filename;
			$dir = substr($fileurl, 0, strrpos($fileurl, '/'));
			$fileurl = $dir.'/'.urlencode(substr($fileurl, strrpos($fileurl, '/')+1));

			$str = '<img src="image/filetype/'.$filetype.'.gif" /><a href="attach-index-'.$extra['aid'].'.htm" onclick="ajaxmenu(this.href, 1)" target="_blank">点击下载'.$orgfilename."</a> {$dateline},下载次数：$downloads";
			$str .= '<br />『<a id="attach'.$extra['aid'].'" name="gvodvideos" href="'.$fileurl.'" target="_blank" style="color:'.COLORALERT.'">在线播放：点这用GVOD播放本片</a>』';
			return $str;
		}else {
			$filename = htmlspecialchars(substr($fileurl, strrpos($fileurl, '/') + 1));
			$orgfilename = !empty($extra['orgfilename']) ? $extra['orgfilename'] : $filename;
			$dir = substr($fileurl, 0, strrpos($fileurl, '/'));
			$fileurl = $dir.'/'.urlencode(substr($fileurl, strrpos($fileurl, '/')+1));

			$str = '<img src="image/filetype/'.$filetype.'.gif" /><a href="attach-index-'.$extra['aid'].'.htm" onclick="ajaxmenu(this.href, 1)" target="_blank">点击下载'.$orgfilename."</a> {$dateline},下载次数：$downloads";
			$str .= in_array($filetype, array('mp3', 'real', 'av')) ? '<br />『<a id="attach'.$extra['aid'].'" name="gvodvideos" href="'.$fileurl.'" target="_blank" style="color:'.COLORALERT.'">在线播放：点这用GVOD播放本片</a>』' : '';
			return $str;
		}
	}

	public function club_file_to_html($fileurl, $filetype, $extra = array(), $imageid=0) {
		if($filetype == 'image') {
			list($imagewidth, $imageheight) = getimagesize($fileurl);
			$rate = $imageheight/$imagewidth;
			$imagewidth = $imagewidth >= 740 ? 740 : $imagewidth;
			$imageheight = intval($rate*$imagewidth);
			$dir = substr($fileurl, 0, strrpos($fileurl, '/'));
			$filename = substr($fileurl, strrpos($fileurl, '/')+1);
			$fileurl = $dir.'/'.urlencode($filename);
			return '<a href="'.XIUNO_HOST_IMAGE.$fileurl.'"'.(isset($extra['align']) ? " align=\"$extra[align]\"" : '').' target="_blank"><img src="'.$fileurl.'" width="'.$imagewidth.'" height="'.$imageheight.'" /></a>'."<!--imageid=$imageid-->";
		} elseif($filetype == 'flash') {
			return '<embed src="'.$fileurl.'" width="400" height="300"></embed>';
		} else {
			$filename = htmlspecialchars(substr($fileurl, 0, strrpos($fileurl, '/')));
			return '<a href="thread-thread_attach-'.$extra['clubaid'].'.htm" onclick="ajaxmenu(this.href, 1)" target="_blank"><img src="image/filetype/'.$filetype.'.gif" />点击下载'.$filename.'</a>';
		}
	}
}

/*
header("Content-type: image/PNG");
$im = imagecreatefrompng("1.png") ;
imagealphablending($im, FALSE);//取消默认的混色模式
imagesavealpha($im,TRUE);//设定保存完整的 alpha 通道信息
imagepng($im);
imagedestroy($im);
*/
?>